package com.component;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.*;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @author fanxiao  2022/3/29
 * @since 1.0.0
 */
public class CandidatesScannerRegitrar implements ImportBeanDefinitionRegistrar {



	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
		AnnotationAttributes annotationAttributes =
				AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(Candidates.class.getName()));
		if (annotationAttributes != null) {
			BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CandidatesScannerConfigurer.class);
			builder.addPropertyValue("basePackage", annotationAttributes.getString("basePackage"));

			Class<?> markerInterface = annotationAttributes.getClass("markerInterface");
			if (!Class.class.equals(markerInterface)) {
				builder.addPropertyValue("markerInterface", markerInterface);
			}
			builder.addPropertyValue("factoryBeanClass", CandidatesFactoryBean.class);
			builder.setScope(AbstractBeanDefinition.SCOPE_DEFAULT);
			builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
			String beanName = importBeanNameGenerator.generateBeanName(builder.getBeanDefinition(), registry);
			registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
		} else {
			throw new BeanDefinitionValidationException("Please check @Candidates annotation attribute");
		}
	}
}